<?php
namespace App\Http\Controllers\Business\Admin\Account;

use App\Models\AllInPayTooles;
use App\Models\Comment;
use App\Models\Order;
use App\Models\OrderRefund;
use App\Models\Recharge;
use App\Models\SalesmanInfo;
use App\Models\SalesmanOrder;
use App\Models\Shop;
use App\Models\ShopAccount;
use App\Models\ShopSalesman;
use App\Models\ShopSalesmanDetail;
use App\Models\SmsMessage;
use App\Models\RedEnvelope;
use App\Models\User;
use App\Models\Refund;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Log;
use App\Http\Controllers\Business\Admin\Log\ShopLog;
use App\Models\AdminUser;

Class AccountManagement{
    //平台流水
    public static function ledgerAccount($startTime = '',$lastTime = '') {
        if (!$startTime || !$lastTime) {
            $startTime = '2016-01-01 00:00:00';
            $lastTime = date('Y-m-d H:i:s', time());
        }
        $data = [];
        //处理用户红包过期状态
        RedEnvelope::where('status', 0)->where('endtime', '<', date('Y-m-d'))->update(['status'=>2]);
        //充值收入
        $income = Recharge::where('created_at','>=',$startTime)->where('created_at','<=',$lastTime)->sum('actualmoney');
        //充值退款金额
        $refundAmount = Refund::where('status', 1)->sum('money');
        //充值退款服务费
        $refundFeeAmount = Refund::where('status', 1)->sum('fee');
        //消费退款金额
        $consumerRefundAmount = Order::where('refundstatus',1)->sum('orderamount');
        $consumerRefundAmount = !empty($consumerRefundAmount)?$consumerRefundAmount/2:'0.00';
        //商家支出
        $cost = ShopAccount::where('created_at','>=',$startTime)->where('created_at','<=',$lastTime)->sum('accountamount');
        //商家待支出
        $waitWithdraw = Order::where('accountstatus', '0')->where('refundstatus', 0)->sum('accountamount');
        //余额
        $balance = User::where('created_at','>=',$startTime)->where('created_at','<=',$lastTime)->sum('balance');
        $balance = round($balance/2, 2);
        //订单退款引起红包的差额
        $redEnvelopeBalanceAfterOrderRefund = RedEnvelope::where('status', 4)->sum('amount');
        $redEnvelopeBalanceAfterOrderRefund = (!$redEnvelopeBalanceAfterOrderRefund) ? 0 : $redEnvelopeBalanceAfterOrderRefund;
        $redEnvelopeBalanceAfterOrderRefund = $redEnvelopeBalanceAfterOrderRefund /2;
        //充值服务费
        $rechargeFeeAmountTotal = Recharge::where('created_at','>=',$startTime)->where('created_at','<=',$lastTime)->sum('fee');
        //充值服务费减去退款服务费
        $rechargeFeeAmount = $rechargeFeeAmountTotal - $refundFeeAmount;
        //代理商服务费和平台服务费
        $agentRechargeFeeAmount = '';
        $platformRechargeFeeAmount = '';
        $usedTotalRedAmount = '';
        $agentTotalRedAmount = '';
        $platformTotalRedAmount = '';
        $cityInfo = AdminUser::where('roleid','4')->orwhere('admin_users.id',30)->join('city','city.id','=','admin_users.cityid')->select('cityid','city.name','agentratio','hqratio')->get();
        foreach($cityInfo as $key=>$value){
            $platformOrderFeeAmount = '';
            $agentOrderFeeAmount = '';
            $orderAmount = Order::where('cityid',$value['cityid'])
                ->where('refundstatus',0)
                ->where('created_at','>=','2017-03-01 00:00:00')
                ->select(DB::RAW("sum(orderamount) as orderamount,DATE_FORMAT(created_at,'%Y-%m-%d') as days"))
                ->groupBy('days')
                ->orderBy('days','desc')
                ->get();
            if(!empty($orderAmount)){
                foreach($orderAmount as $k=>$v){
                    $platformFee = $v['orderamount']/2*($value['hqratio']/100)*ENV('RECHARGE_FEE');
                    $platformOrderFeeAmount = $platformOrderFeeAmount + sprintf("%.2f",substr($platformFee,0,(stripos($platformFee,'.')+3)));
                    $agentFee = $v['orderamount']/2*($value['agentratio']/100)*ENV('RECHARGE_FEE');
                    $agentOrderFeeAmount = $agentOrderFeeAmount +  sprintf("%.2f",substr($agentFee,0,(stripos($agentFee,'.')+3)));
                }
            }
            $platformRechargeFeeAmount = $platformRechargeFeeAmount + $platformOrderFeeAmount;
            $agentRechargeFeeAmount = $agentRechargeFeeAmount + $agentOrderFeeAmount;

            //处理红包，获取已使用红包，代理商红包，平台红包
            $usedRedEnvelopesTotal = '';
            $platformUsedRedEnvelopes = '';
            $agentUsedRedEnvelopes = '';
            $usedRedEnvelopes = RedEnvelope::where('cityid',$value['cityid'])
                ->where(function($query) {
                    $query->orwhere('red_envelopes.status', 1)->orwhere('red_envelopes.status', 4);
                })
                ->where('red_envelopes.created_at','>=','2017-03-01 00:00:00')
                ->select(DB::raw("sum(91fbw_red_envelopes.amount) as amount,DATE_FORMAT(91fbw_red_envelopes.usetime,'%Y-%m-%d') as days,cityid"))
                ->groupBy('red_envelopes.cityid','days')
                ->get();
            if(!empty($usedRedEnvelopes)){
                foreach($usedRedEnvelopes as $k=>$v){
                    //已使用的红包
                    $usedRedEnvelopesTotal = $usedRedEnvelopesTotal + sprintf("%.2f",substr(($v['amount']/2),0,(stripos(($v['amount']/2),'.')+3)));
                    //平台红包
                    $platformRedAmount = $v['amount']/2*$value['hqratio']/100;
                    $platformUsedRedEnvelopes = $platformUsedRedEnvelopes + sprintf("%.2f",substr($platformRedAmount,0,(stripos($platformRedAmount,'.')+3)));
                    //代理商红包
                    $agentRedAmount = $v['amount']/2*$value['agentratio']/100;
                    $agentUsedRedEnvelopes = $agentUsedRedEnvelopes + sprintf("%.2f",substr($agentRedAmount,0,(stripos($agentRedAmount,'.')+3)));
                }
            }
            $usedTotalRedAmount = $usedTotalRedAmount + $usedRedEnvelopesTotal;
            $agentTotalRedAmount = $agentTotalRedAmount + $agentUsedRedEnvelopes;
            $platformTotalRedAmount = $platformTotalRedAmount + $platformUsedRedEnvelopes;
        }
        //未消费的服务费    充值服务费（元）=【代理商】服务费收入（元）+【平台】服务费收入（元）+未消费的服务费（元）
        $nonConsumptionFeeAmount = $rechargeFeeAmount - $agentRechargeFeeAmount - $platformRechargeFeeAmount;
        //已使用红包和平台红包及代理商红包
        $differenceAmount = $usedTotalRedAmount - $platformTotalRedAmount - $agentTotalRedAmount;
        $differenceAmount = sprintf("%.2f",substr($differenceAmount,0,(stripos($differenceAmount,'.')+3)));
        //服务费收益
        $feeIncome = $rechargeFeeAmount - $usedTotalRedAmount;
        $data = [
            'income' => $income,
            'cost' => $cost,
            'refundamount' => $refundAmount,
            'refundfeeamount' => $refundFeeAmount,
            'consumerrefundamount'=>$consumerRefundAmount,
            'waitwithdraw' => $waitWithdraw,
            'balance' => $balance,
            'rechargefeeamount' => $rechargeFeeAmount,
            'platformrechargefeeamount' => $platformRechargeFeeAmount,
            'agentrechargefeeamount' => $agentRechargeFeeAmount,
            'nonconsumptionfeeamount'=>$nonConsumptionFeeAmount,
            'usedredenvelopestotal'=>$usedTotalRedAmount,
            'agentusedredenvelopes'=>$agentTotalRedAmount,
            'platformusedredenvelopes'=>$platformTotalRedAmount,
            'differenceamount'=>$differenceAmount,
            'feeincome' => $feeIncome,
            'redenvelopebalanceafterorderrefund' => $redEnvelopeBalanceAfterOrderRefund
        ];
        return ['status'=>'success','data'=>$data];
    }
    //用户退款
    public static function refund($mobile, $money, $fee, $note='') {
        if(!$mobile||(strlen($mobile) != 11)||!$money||($money==0)||($money == 0.0) ||($money == 0.00)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $user = User::where('mobile', $mobile)->first();
        if(!$user) {
            return ['status'=>'failed', 'message'=>'获取信息错误'];
        }
        //生成退单
        $startBalance = $user['balance'];
        if($startBalance < 2*$money) {
            return ['status'=>'failed', 'message'=>'余额不足'];
        }
        $lastBalance = round($startBalance - 2*$money, 2);
        $rechargeFee = env('RECHARGE_FEE');
        if($fee > round($rechargeFee*$money,2)) {
            return ['status'=>'failed', 'message'=>'服务费高于金额乘以'.$rechargeFee];
        }
        $actualMoney = $money + $fee;
        $refund = Refund::create([
            'userid' => $user['id'],
            'money' => $money,
            'fee' => $fee,
            'actualmoney' => $actualMoney,
            'startbalance' => $startBalance,
            'lastbalance' => $lastBalance,
            'note' => $note,
            'status' => 1,
            'adminid' => Auth::guard('adminweb')->id()
        ]);
        $refund->save();
        //减少余额
        $user->balance = $lastBalance;
        $user->save();
        return ['status'=>'success', 'message'=>'退款成功'];
    }
    //输入手机号码获取最近几笔充值记录
    public static function getRechargeByMobile($mobile, $skip=0, $take=10) {
        if(!$mobile || (strlen($mobile) != 11)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $user = User::where('mobile', $mobile)->first();
        if(!$user) {
            return ['status'=>'failed', 'message'=>'获取用户信息错误'];
        }
        $userId = $user['id'];
        $nickName = $user['nickname'];
        $balance = $user['balance'];
        $lists = Recharge::where('userid', $userId)->orderBy('created_at', 'desc')->skip($skip)->take($take)
            ->select('created_at', 'money', 'fee', 'actualmoney')->get();
        $fee = 0.00;
        foreach($lists as $list) {
            $fee += $list['fee'];
        }
        $data = [
            'nickname' => $nickName,
            'balance' => $balance,
            'fee' => $fee,
            'lists' => $lists
        ];
        return ['status'=>'succes', 'data'=>$data];
    }
    //用户充值
    public static function userRecharge($mobile,$money,$note = '') {
        if(!$mobile || !$money || $money < 0) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $userid = User::where('mobile',$mobile)->pluck('id')->first();
        if(!$userid) {
            return ['status' => 'failed', 'message' => '账号错误！'];
        }
        $tenMinutesAgo = date('Y-m-d H:i:s', time() - 10*60);
        if(Recharge::where('userid', $userid)->where('created_at', '>=', $tenMinutesAgo)->get()->count()) {
            return ['status'=>'failed', 'message'=>'十分钟内只能充一笔'];
        }
        $mobile = substr($mobile, 8, 10);
        $rand = '';
        for ($i = 0; $i < 4; $i++) {
            $rand .= rand(0, 9);
        }
        $ordernumber = '3' . date('ymdHis', time()) . $rand . $mobile;
        if(!Recharge::where('userid',$userid)->first()) {
            $firstrechargetime = User::find($userid);
            $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
            $firstrechargetime->save();
        }
        $recharge = new Recharge;
        $recharge->userid = $userid;
        $recharge->money = $money;
        $recharge->fee = 0.00;
        $recharge->actualmoney = $money;
        $recharge->status = '1';
        $recharge->path = '后台充值';
        $recharge->rechargenumber = $ordernumber;
        $recharge->doublemoney = $money * 2;
        $recharge->doublestatus = '1';
        $recharge->doubletime = date('Y-m-d H:i:s', time());
        User::find($userid)->increment('balance',$money*2);
        User::find($userid)->increment('point',$money);
        $recharge->sharestatus = '0';
        $recharge->note = $note;
        $recharge->adminid = Auth::guard('adminweb')->id();
        $recharge->save();
        return ['status'=>'success', 'message'=>'充值成功'];
    }
    //用户对账单
    public static function userStatement($starttime = '',$lasttime = '',$mobile = '%',$perpage = 20) {
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if($mobile != '%') {
            $mobile = '%'.$mobile.'%';
            $userIdArray = [];
            $users = User::where('mobile','like',$mobile)->select('id')->paginate($perpage);
            foreach($users as $user) {
                if(!in_array($user['id'], $userIdArray)) {
                    array_push($userIdArray, $user['id']);
                }
            }
            $data['data'] = User::where('mobile','like',$mobile)->select('id as userid','mobile','nickname','balance')->paginate($perpage);
            $data['rechargenum'] = Recharge::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->get()->count();
            $data['rechargemoney'] = Recharge::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
            $data['ordernum'] = Order::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->get()->count();
            $data['ordermoney'] = Order::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
            $data['balance'] = User::whereIn('id',$userIdArray)->sum('balance');
            foreach ($data['data'] as $k=>$v) {
                $data['data'][$k]['rechargemoney'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
                $data['data'][$k]['isdouble'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','1')->sum('doublemoney');
                $data['data'][$k]['notdouble'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','0')->sum('doublemoney');
                $data['data'][$k]['actualamount'] = Order::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
            }
            return ['status'=>'success','data'=>$data];
        } else {
            $userIdArray = [];
            $users = User::select('id')->paginate($perpage);
            foreach($users as $user) {
                if(!in_array($user['id'], $userIdArray)) {
                    array_push($userIdArray, $user['id']);
                }
            }
            $data['data'] = User::select('id as userid','mobile','nickname','balance')->paginate($perpage);
            $data['rechargenum'] = Recharge::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->get()->count();
            $data['rechargemoney'] = Recharge::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
            $data['ordernum'] = Order::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->get()->count();
            $data['ordermoney'] = Order::whereIn('userid',$userIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
            $data['balance'] = User::whereIn('id',$userIdArray)->sum('balance');
            foreach ($data['data'] as $k=>$v) {
                $data['data'][$k]['rechargemoney'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
                $data['data'][$k]['isdouble'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','1')->sum('doublemoney');
                $data['data'][$k]['notdouble'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','0')->sum('doublemoney');
                $data['data'][$k]['actualamount'] = Order::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
            }
            return ['status'=>'success','data'=>$data];
        }
    }
    //新的用户对账单
    public static function newUserStatement($starttime,$lasttime,$perpage = 20) {
        if(!$starttime || !$lasttime) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $userIds = [];
        $users = Order::where('created_at', '>=', $starttime)->where('created_at', '<=', $lasttime)->where('refundstatus', 0)->select('userid')->get();
        foreach($users as $list) {
            if(!in_array($list['userid'], $userIds)) {
                array_push($userIds, $list['userid']);
            }
        }
        $rechargeUsers = Recharge::where('status', '1')->where('created_at', '>=', $starttime)->where('created_at', '<=', $lasttime)->select('userid')->get();
        foreach($rechargeUsers as $list) {
            if(!in_array($list['userid'], $userIds)) {
                array_push($userIds, $list['userid']);
            }
        }
        $data['data'] = User::where('firstrechargetime', '!=', '0000-00-00 00:00:00')->whereIn('id', $userIds)->select('id as userid','mobile','nickname','balance')->paginate($perpage);
        $data['rechargenum'] = Recharge::whereIn('userid',$userIds)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->get()->count();
        $data['rechargemoney'] = Recharge::whereIn('userid',$userIds)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
        $data['ordernum'] = Order::whereIn('userid',$userIds)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->get()->count();
        $data['ordermoney'] = Order::whereIn('userid',$userIds)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
        $data['doublemoney'] = Recharge::where('doublestatus', '0')->where('created_at', '>=', $starttime)->where('created_at','<=', $lasttime)->whereIn('userid', $userIds)->sum('doublemoney');
        $data['balance'] = User::where('firstrechargetime', '!=', '0000-00-00 00:00:00')->whereIn('id',$userIds)->sum('balance');
        foreach ($data['data'] as $k=>$v) {
            $data['data'][$k]['rechargemoney'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
            $data['data'][$k]['isdouble'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','1')->sum('doublemoney');
            $data['data'][$k]['notdouble'] = Recharge::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','0')->sum('doublemoney');
            $data['data'][$k]['actualamount'] = Order::where('userid',$data['data'][$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
        }
        return ['status'=>'success','data'=>$data];
    }
    //导出用户对账单
    public static function exportUserStatement($starttime, $lasttime) {
        if(!$starttime || !$lasttime) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $userIds = [];
        $users = Order::where('created_at', '>=', $starttime)->where('created_at', '<=', $lasttime)->where('refundstatus', 0)->select('userid')->get();
        foreach($users as $list) {
            if(!in_array($list['userid'], $userIds)) {
                array_push($userIds, $list['userid']);
            }
        }
        $rechargeUsers = Recharge::where('status', '1')->where('created_at', '>=', $starttime)->where('created_at', '<=', $lasttime)->select('userid')->get();
        foreach($rechargeUsers as $list) {
            if(!in_array($list['userid'], $userIds)) {
                array_push($userIds, $list['userid']);
            }
        }
        $data = User::whereIn('id', $userIds)->select('id as userid','mobile','nickname','balance')->get();
        foreach ($data as $k=>$v) {
            $data[$k]['rechargemoney'] = Recharge::where('userid',$data[$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
            $data[$k]['isdouble'] = Recharge::where('userid',$data[$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','1')->sum('doublemoney');
            $data[$k]['notdouble'] = Recharge::where('userid',$data[$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','0')->sum('doublemoney');
            $data[$k]['actualamount'] = Order::where('userid',$data[$k]['userid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
        }
        return ['status'=>'success','data'=>$data];
    }
    //通过userid 获取用户充值列表
    public static function userRechargeList($userid,$type = '%',$doublestatus = '%',$starttime = '',$lasttime = '') {
        if(!$userid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if($type != '%') {
            $type = '%' . $type . '%';
        }
        if($doublestatus != '%') {
            $doublestatus = '%' . $doublestatus . '%';
        }
        $data['userinfo'] = User::where('id', $userid)->select('nickname', 'mobile', 'balance')->first();
        $data['rechargenum'] = Recharge::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->get()->count();
        $data['rechargemoney'] = Recharge::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('money');
        $data['isdouble'] = Recharge::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','1')->sum('doublemoney');
        $data['notdouble'] = Recharge::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('doublestatus','0')->sum('doublemoney');
        $data['data'] = Recharge::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)
            ->where('path','like',$type)->where('doublestatus','like',$doublestatus)
            ->select('id as rechargeid', 'rechargenumber','money','doublemoney','doublestatus','path','isdoublecoupons','sharestatus','created_at','doubletime')
            ->get();
        return ['status'=>'success','data'=>$data];
    }
    //通过userid 获取用户订单列表
    public static function userOrderList($userid,$search = '%',$starttime = '',$lasttime = '') {
        if(!$userid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if($search != '%') {
            $search = '%' . $search . '%';
        }
        $GLOBALS['search'] = $search;
        $data['userinfo'] = User::where('id', $userid)->select('nickname', 'mobile', 'balance')->first();
        $data['ordernum'] = Order::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->get()->count();
        $data['orderamount'] = Order::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('orderamount');
        $data['fee'] = Order::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('fee');
        $data['actualamount'] = Order::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('actualamount');
        $data['redenvelopeamount'] = Order::where('userid',$userid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('redenvelopeamount');
        $data['data'] = Order::where('orders.userid',$userid)->where('orders.created_at','>=',$starttime)->where('orders.created_at','<=',$lasttime)->where('orders.refundstatus', 0)
            ->select('shops.name as shopname','shops.code as shopcode','orders.orderamount','orders.fee','orders.actualamount','orders.redenvelopeamount','orders.created_at')
            ->join('shops','shops.id','=','orders.shopid')
            ->where(function($query){
                $query->orWhere('shops.name','like',$GLOBALS['search'])
                    ->orWhere('shops.code','like',$GLOBALS['search']);
            })
            ->get();
        return ['status'=>'success','data'=>$data];
    }
    //商家银行帐号管理
    public static function shopBankManagement($perpage=20,$cityId) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = Shop::where('shops.cityid',$cityId)->orderBy('shops.updated_at', 'desc')
            ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
            ->select('shops.id as shopid', 'shops.code', 'shops.name', 'shops.cityname','shops.parentmobile', 'admin_users.realname as adminname', 'shops.bankcard', 'shops.cardholder', 'shops.bankname', 'shops.bankprovince', 'shops.bankcity', 'shops.opencardbank')
            ->paginate($perpage);
        return ['status'=>'success', 'data'=>$data];
    }
    //通过商家id 获取商家银行卡
    public static function getShopBank($shopId) {
        if(!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = Shop::where('shops.id', $shopId)
            ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
            ->select('shops.id as shopid', 'shops.code', 'shops.name', 'shops.parentmobile', 'admin_users.realname as adminname', 'shops.bankcard', 'shops.cardholder', 'shops.bankname', 'shops.bankprovince', 'shops.bankcity', 'shops.opencardbank','shops.idcard')
            ->first();
        return ['status'=>'success', 'data'=>$data];
    }
    //编辑商家银行信息
    public static function editShopBank($shopId, $cardholder, $bankcard, $bankName, $bankProvince, $bankCity, $openCardBank='',$idcard = '') {
        if(!$shopId|| !$bankcard||!$cardholder||!$bankName||!$bankProvince||!$bankCity) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $shopInfo = Shop::where('id',$shopId)->select('code','name','parentmobile','parentname','cardholder','bankcard','bankname','opencardbank','bankprovince','bankcity','idcard')->first();
        $data = [
            'bankcard' => $bankcard,
            'cardholder' => $cardholder,
            'bankname' => $bankName,
            'bankprovince' => $bankProvince,
            'bankcity' => $bankCity,
            'opencardbank' => $openCardBank,
            'idcard'=>$idcard
        ];
        $updateShop = Shop::where('id', $shopId)->update($data);
        //if(!empty($updateShop)){
            $reason = '';
            if(strcmp($shopInfo['bankcard'],$bankcard) != '0'){
                $reason .= '银行卡号由"'.$shopInfo['bankcard'].'"修改成"'.$bankcard.'";';
            }
            if(strcmp($shopInfo['cardholder'],$cardholder) != '0'){
                $reason .= '持卡人由"'.$shopInfo['cardholder'].'"改成"'.$cardholder.'";';
            }
            if(strcmp($shopInfo['bankname'],$bankName) != '0'){
                $reason .= '银行名称由"'.$shopInfo['bankname'].'"改成"'.$bankName.'";';
            }
            if(strcmp($shopInfo['idcard'],$idcard) != '0'){
                $reason .= '身份证号由"'.$shopInfo['idcard'].'"改成"'.$idcard.'";';
            }
            if(strcmp($shopInfo['bankprovince'],$bankProvince) != '0'){
                $reason .= '银行卡所属省份由"'.$shopInfo['bankprovince'].'"改成"'.$bankProvince.'";';
            }
            if(strcmp($shopInfo['bankcity'],$bankCity) != '0'){
                $reason .= '银行卡所属市区由"'.$shopInfo['bankcity'].'"改成"'.$bankCity.'";';
            }
            if(strcmp($shopInfo['opencardbank'],$openCardBank) != '0'){
                $reason .= '银行开户行由"'.$shopInfo['opencardbank'].'"改成"'.$openCardBank.'";';
            }
            $reason = rtrim($reason, ";") ;
            $shopLog = ShopLog::writeShopLog($shopId,'update_shop_account',0,$reason,'');
       // }
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //商家对账单
    public static function shopStatement($starttime = '',$lasttime = '',$search = '%',$perpage = 20) {
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if($search != '%') {
            $search = '%'.$search.'%';
        }
        $GLOBALS['search'] = $search;
        $shopIdArray = [];
        $shops = Shop::where('name','like',$search)->orWhere('name','like',$search)->orWhere('code','like',$search)->select('id')->paginate($perpage);
        foreach($shops as $shop) {
            if(!in_array($shop['id'], $shopIdArray)) {
                array_push($shopIdArray, $shop['id']);
            }
        }
        $data['data'] = Shop::where('name','like',$search)->orWhere('name','like',$search)->orWhere('code','like',$search)
            ->select('id as shopid','name as shopname','code as shopcode','firstclassname','secondclassname')->paginate($perpage);
        $data['ordernum'] = Order::whereIn('shopid',$shopIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->get()->count();
        $data['shopamount'] = Order::whereIn('shopid',$shopIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('shopamount');
        $data['redenvelopeamount'] = Order::whereIn('shopid',$shopIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('redenvelopeamount');
        $data['accountamount'] = Order::whereIn('shopid',$shopIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('accountamount');
        $data['iswithdraw'] = Order::whereIn('shopid',$shopIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->where('accountstatus','1')->sum('accountamount');
        $data['notwithdraw'] = Order::whereIn('shopid',$shopIdArray)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->where('accountstatus','0')->sum('accountamount');
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['shopamount'] = Order::where('shopid',$data['data'][$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('shopamount');
            $data['data'][$k]['redenvelopeamount'] = Order::where('shopid',$data['data'][$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('redenvelopeamount');
            $data['data'][$k]['accountamount'] = Order::where('shopid',$data['data'][$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('accountamount');
            $data['data'][$k]['iswithdraw'] = Order::where('shopid',$data['data'][$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->where('status','1')->sum('accountamount');
            $data['data'][$k]['notwithdraw'] = Order::where('shopid',$data['data'][$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->where('status','0')->sum('accountamount');
        }
        return ['status'=>'success','data'=>$data];
    }
    //新的商家对账单统计数据
    public static function shopStatementStatistic($cityId, $startTime, $lastTime, $search='')
    {
        if (!$cityId || !$startTime || !$lastTime) {
            return ['status' => 'failed', 'message' => '参数错误'];
        }
        if ($search) {
            $GLOBALS['search'] = $search;
            $shopIds = Order::where('orders.cityid', $cityId)->where('orders.created_at', '>=', $startTime)->where('orders.created_at', '<=', $lastTime)->where('orders.refundstatus', 0)
                ->join('shops', 'orders.shopid', '=', 'shops.id')
                ->where(function($query){
                    $query->orwhere('shops.name', 'like', '%'.$GLOBALS['search']. '%')->orwhere('code', $GLOBALS['search']);
                })->distinct('orders.shopid')->pluck('orders.shopid');
            $orderNum = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->get()->count();
            $shopAmount = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->sum('shopamount');
            $redEnvelopeAmount = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->sum('redenvelopeamount');
            $accountAmount = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->sum('accountamount');
            $isWithdraw = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->where('accountstatus', 1)->sum('accountamount');
            $notWithdraw = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->where('accountstatus', 0)->sum('accountamount');
        } else {
            $shopIds = Order::where('cityid', $cityId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->where('refundstatus', 0)->distinct('shopid')->pluck('shopid');
            $orderNum = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->get()->count();
            $shopAmount = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->sum('shopamount');
            $redEnvelopeAmount = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->sum('redenvelopeamount');
            $accountAmount = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->sum('accountamount');
            $isWithdraw = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->where('accountstatus', 1)->sum('accountamount');
            $notWithdraw = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->where('refundstatus', 0)->where('accountstatus', 0)->sum('accountamount');
        }
        $data = [
            'shopnum' => count($shopIds),
            'ordernum' => $orderNum,
            'shopamount' => $shopAmount,
            'redenvelopeamount' => $redEnvelopeAmount,
            'accountamount' => $accountAmount,
            'iswithdraw' => $isWithdraw,
            'notwithdraw' => $notWithdraw
        ];
        return ['status'=>'success', 'data'=>$data];

    }
    //新的商家对账单列表
    public static function shopStatementList($cityId, $startTime, $lastTime, $page=1, $length=50, $search='') {
        if(!$cityId || !$startTime || !$lastTime) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = [];
        $skip = ($page - 1) * $length;
        if($search) {
            $GLOBALS['search'] = $search;
            $shopIds = Order::where('orders.cityid', $cityId)->where('orders.created_at', '>=', $startTime)->where('orders.created_at', '<=', $lastTime)->where('orders.refundstatus', 0)
                ->join('shops', 'orders.shopid', '=', 'shops.id')
                ->where(function($query){
                    $query->orwhere('shops.name', 'like', '%'.$GLOBALS['search']. '%')->orwhere('code', $GLOBALS['search']);
                })->distinct('orders.shopid')->pluck('orders.shopid');
        } else {
            $shopIds = Order::where('cityid', $cityId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->where('refundstatus', 0)
                ->distinct('shopid')->skip($skip)->take($length)->pluck('shopid');
        }
        foreach($shopIds as $shopId) {
            $detailResult = self::getShopStatementDetailByShopId($shopId, $startTime, $lastTime);
            if($detailResult['status'] == 'success') {
                array_push($data, $detailResult['data']);
            }
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //通过shopid获取商家对账信息
    public static function getShopStatementDetailByShopId($shopId, $startTime, $lastTime) {
        if(!$shopId || !$startTime || !$lastTime) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }

        $data = Order::where('shopid', $shopId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->where('refundstatus', 0)
            ->select(DB::raw('sum(shopamount) as shopamountsum'),DB::raw('sum(redenvelopeamount) as redenvelopeamountsum'),DB::raw('sum(accountamount) as accountamountsum'))->first();
        $data['iswithdrawsum'] = Order::where('shopid', $shopId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->where('refundstatus', 0)->where('status', 1)->sum('accountamount');
        $data['notwithdrawsum'] = Order::where('shopid', $shopId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->where('refundstatus', 0)->where('status', 0)->sum('accountamount');
        $shop = Shop::where('id', $shopId)->select('id as shopid','name as shopname','code as shopcode','firstclassname','secondclassname')->first();
        if(!$shop) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $data['shopid'] = $shop->shopid;
        $data['shopname'] = $shop->shopname;
        $data['shopcode'] = $shop->shopcode;
        $data['firstclassname'] = $shop->firstclassname;
        $data['secondclassname'] = $shop->secondclassname;
        return ['status'=>'success', 'data'=>$data];
    }
    //导出新的商家对账单
    public static function exportShopStatement($starttime,$lasttime) {
        if(!$starttime || !$lasttime) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $shopIds = [];
        $shops = Order::where('created_at', '>=', $starttime)->where('created_at', '<=', $lasttime)->select('shopid')->get();
        foreach($shops as $list) {
            if(!in_array($list['shopid'], $shopIds)) {
                array_push($shopIds, $list['shopid']);
            }
        }
        $data = Shop::whereIn('id', $shopIds)->select('id as shopid','name as shopname','code as shopcode','firstclassname','secondclassname')->get();
        foreach ($data as $k => $v) {
            $data[$k]['shopamount'] = Order::where('shopid',$data[$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('shopamount');
            $data[$k]['redenvelopeamount'] = Order::where('shopid',$data[$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('redenvelopeamount');
            $data[$k]['accountamount'] = Order::where('shopid',$data[$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->sum('accountamount');
            $data[$k]['iswithdraw'] = Order::where('shopid',$data[$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('accountstatus','1')->sum('accountamount');
            $data[$k]['notwithdraw'] = Order::where('shopid',$data[$k]['shopid'])->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('accountstatus','0')->sum('accountamount');
        }
        return ['status'=>'success','data'=>$data];
    }
    //商家订单列表
    public static function shopOrderList($shopid,$starttime = '',$lasttime = '',$mobile = '%') {
        if(!$shopid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        if (!$starttime || !$lasttime) {
            $starttime = '2016-01-01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if($mobile != '%') {
            $mobile = '%'.$mobile.'%';
        }
        $data['shopinfo'] = Shop::where('id', $shopid)->select('code', 'name')->first();
        $data['ordernum'] = Order::where('shopid',$shopid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->get()->count();
        $data['shopamount'] = Order::where('shopid',$shopid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('shopamount');
        $data['redenvelopeamount'] = Order::where('shopid',$shopid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('redenvelopeamount');
        $data['accountamount'] = Order::where('shopid',$shopid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->sum('accountamount');
        $data['iswithdraw'] = Order::where('shopid',$shopid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->where('status','1')->sum('accountamount');
        $data['notwithdraw'] = Order::where('shopid',$shopid)->where('created_at','>=',$starttime)->where('created_at','<=',$lasttime)->where('refundstatus', 0)->where('status','0')->sum('accountamount');
        $data['data'] = Order::where('users.mobile','like',$mobile)->where('orders.shopid',$shopid)->where('orders.created_at','>=',$starttime)->where('orders.refundstatus', 0)
            ->where('orders.created_at','<=',$lasttime)->join('users','orders.userid','=','users.id')
            ->select('orders.created_at','users.mobile','users.nickname','orders.shopamount','orders.redenvelopeamount','orders.accountamount','orders.accountstatus','orders.accounttime')
            ->get();
        return ['status'=>'success','data'=>$data];
    }
    //更新商家待提现的数据，并返回该订单的总数和金额
    public static function shopWaitWithdrawCount($search='',$cityId) {
        if(!$cityId){
            return ['status'=>'failed','message'=>'参数错误'];
        }
        //更新待提现的数据
        $week = date("w",time());
        if($week == '1' or $week == '2') {
            $diffday = 5;
        } else {
            $diffday = 3;
        }
        $lasttime = date('Y-m-d',time() - 86400 * $diffday) . ' 23:59:59';
        $shopids = Order::where('orders.created_at','<=',$lasttime)->where('orders.accountstatus','0')->where('orders.refundstatus', 0)->select('shopid')->distinct('shopid')->get();
        if($shopids) {
            foreach ($shopids as $v) {
                $shopamount = 0;
                $orderid = '';
                $order = Order::where('orders.created_at', '<=', $lasttime)->where('orders.accountstatus', '0')->where('orders.refundstatus', 0)
                    ->where('shopid', $v['shopid'])->select('id', 'accountamount')->get();
                foreach ($order as $value) {
                    $orderid = $orderid . $value['id'] . ',';
                    $shopamount = $shopamount + $value['accountamount'];
                }
                Order::where('orders.created_at', '<=', $lasttime)->where('orders.accountstatus', '0')->where('orders.refundstatus', 0)
                    ->where('shopid', $v['shopid'])->update(array('status' => '1','accountstatus' => '1', 'accounttime' => date('Y-m-d H:i:s', time()), 'adminid' => Auth::guard('adminweb')->id()));
                $orderid = substr($orderid, 0, strlen($orderid) - 1);
                $shopaccount = new ShopAccount;
                $shopaccount->shopid = $v['shopid'];
                $shopaccount->orderid = $orderid;
                $shopaccount->accountamount = $shopamount;
                $allinpaynumber = $v['shopid'] . time();
                $rand = '';
                for($i = 0;$i < (20 - strlen($allinpaynumber));$i++)
                {
                    $rand = $rand . rand(0,9);
                }
                $allinpaynumber = $allinpaynumber . $rand;
                $shopaccount->allinpaynumber = $allinpaynumber;
                $shopaccount->adminid = Auth::guard('adminweb')->id();
                $shopaccount->save();
            }
        }
        if($search == '') {
            $count = ShopAccount::where('shop_accounts.status', '<>', '1')->where('shops.cityid',$cityId)->join('shops','shops.id','=','shop_accounts.shopid')->get()->count();
            $shopAmount = ShopAccount::where('shop_accounts.status', '<>', '1')->where('shops.cityid',$cityId)->join('shops','shops.id','=','shop_accounts.shopid')->sum('accountamount');
            $failedCount = ShopAccount::where('shop_accounts.status', '2')->where('shops.cityid',$cityId)->join('shops','shops.id','=','shop_accounts.shopid')->get()->count();
        } else {
            $GLOBALS['search'] = $search;
            $count = ShopAccount::where('shop_accounts.status', '<>', '1')
                ->where('shops.cityid',$cityId)
                ->join('shops', 'shop_accounts.shopid', '=', 'shops.id')
                ->where(function($query) {
                    $query->orWhere('shops.name', 'like', '%'.$GLOBALS['search'] . "%")
                        ->orWhere('shops.code', $GLOBALS['search'])
                        ->orWhere('shops.bankcard', $GLOBALS['search'])
                        ->orWhere('shops.cardholder', $GLOBALS['search']);
                })->get()->count('shop_accounts.id');
            $shopAmount = ShopAccount::where('shop_accounts.status', '<>'. '1')
                ->where('shops.cityid',$cityId)
                ->join('shops', 'shop_accounts.shopid', '=', 'shops.id')
                ->where(function($query) {
                    $query->orWhere('shops.name', 'like', '%'.$GLOBALS['search'] . "%")
                        ->orWhere('shops.code', $GLOBALS['search'])
                        ->orWhere('shops.bankcard', $GLOBALS['search'])
                        ->orWhere('shops.cardholder', $GLOBALS['search']);
                })->sum('shop_accounts.accountamount');
            $failedCount = ShopAccount::where('shop_accounts.status', '2')
                ->where('shops.cityid',$cityId)
                ->join('shops', 'shop_accounts.shopid', '=', 'shops.id')
                ->where(function($query) {
                    $query->orWhere('shops.name', 'like', '%'.$GLOBALS['search'] . "%")
                        ->orWhere('shops.code', $GLOBALS['search'])
                        ->orWhere('shops.bankcard', $GLOBALS['search'])
                        ->orWhere('shops.cardholder', $GLOBALS['search']);
                })->get()->count('shop_accounts.id');
        }
        $data = [
            'count' => $count,
            'shopamount' => $shopAmount,
            'failedcount' => $failedCount
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //商家待提现列表
    public static function shopWaitWithdrawList($search, $page=1, $length=50,$cityId) {
        if(!$cityId){
            return ['status'=>'failed','message'=>'参数错误'];
        }
        $skip = ($page - 1) * $length;
        if($search == '') {
            $data = ShopAccount::where('shop_accounts.status', '<>', '1')
                ->where('shops.cityid',$cityId)
                ->join('shops', 'shop_accounts.shopid', '=', 'shops.id')
                ->select('shop_accounts.id as shopaccountid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.cardholder', 'shops.bankname', 'shops.bankcard', 'shops.bankprovince', 'shops.bankcity', 'shops.opencardbank', 'shop_accounts.accountamount', 'shop_accounts.content')
                ->skip($skip)->take($length)->get();
        } else {
            $GLOBALS['search'] = $search;
            $data = ShopAccount::where('shop_accounts.status', '<>', '1')
                ->where('shops.cityid',$cityId)
                ->join('shops', 'shop_accounts.shopid', '=', 'shops.id')
                ->where(function($query) {
                    $query->orWhere('shops.name', 'like', '%'.$GLOBALS['search'] . "%")
                        ->orWhere('shops.code', $GLOBALS['search'])
                        ->orWhere('shops.bankcard', $GLOBALS['search'])
                        ->orWhere('shops.cardholder', $GLOBALS['search']);
                })
                ->select('shop_accounts.id as shopaccountid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.cardholder', 'shops.bankname', 'shops.bankcard', 'shops.bankprovince', 'shops.bankcity', 'shops.opencardbank', 'shop_accounts.accountamount', 'shop_accounts.content')
                ->skip($skip)->take($length)->get();
        }
        return ['status'=>'success','data'=>$data];
    }
    //商家开始提现
    public static function shopStartWithdraw($cityId) {
        if(!$cityId){
            return ['status'=>'failed','message'=>'参数错误'];
        }
        $week = date("w",time());
        if($week == '1' or $week == '2') {
            $diffday = 5;
        } else {
            $diffday = 3;
        }
        $lasttime = date('Y-m-d',time() - 86400 * $diffday) . ' 23:59:59';
        $data = ShopAccount::where('shop_accounts.status','<>','1')
            ->where('shops.cityid',$cityId)
            ->join('shops','shop_accounts.shopid','=','shops.id')
            //->select('shops.bankcard as `收款账户列`','shops.cardholder as `收款户名列`',DB::raw('SUM(accountamount) as `转账金额列`'),'shops.bankname as `收款银行列`','shops.opencardbank as `收款银行支行列`','shops.bankprovince as `收款省/直辖市列`','shops.bankcity as `收款市县列`')
            ->select('shops.bankcard','shops.cardholder','shop_accounts.accountamount','shops.bankname','shops.code','shops.opencardbank','shops.bankprovince','shops.bankcity')
            ->get();
        return ['status'=>'success','data'=>$data];
    }
    //shop_account中的状态status: 0为未打款，1为打款成功，2为打款失败，3为正在打款
    public static function shopWithdraw($shopaccountid) {
        $data = ShopAccount::where('id',$shopaccountid)
            ->where('status','<>','1')
            ->first();
        if($data['status'] == '0' || $data['status'] == '2') {
            ShopAccount::where('id',$shopaccountid)->update(['status'=>'3']);
            $shop = Shop::where('id',$data['shopid'])->first();
            if(!$shop) {
                return ['status'=>'failed','message'=>'打款失败！'];
            }
            $allinpaytooles = new AllInPayTooles();
            if($data['status'] == '0') {
                $allinpaynumber = $data['allinpaynumber'];
            } else {
                $allinpaynumber = $data['shopid'] . time();
                $rand = '';
                for($i = 0;$i < (20 - strlen($allinpaynumber));$i++)
                {
                    $rand = $rand . rand(0,9);
                }
                $allinpaynumber = $allinpaynumber . $rand;
            }
            $result = $allinpaytooles->getPayActionModel($allinpaynumber,$data['shopid'],$data['accountamount'],$shop['bankcard'],$shop['cardholder'],'翻贝网商户结算款','翻贝网用户消费款结算至商户');
            if($result['AIPG']['INFO']['RET_CODE'] == '0000') {
                ShopAccount::where('id',$shopaccountid)
                    ->update(['allinpaynumber'=>$allinpaynumber,'status'=>'1','content'=>$result['AIPG']['INFO']['ERR_MSG'],'contentjson'=>json_encode($result),'bankcard'=>$shop['bankcard'],'cardholder'=>$shop['cardholder'],'accounttime'=>date('Y-m-d H:i:s',time())]);
                SmsMessage::accountToShop($shop['smsphone'],$shop['name'],$data['accountamount'],substr($shop['bankcard'], -4));
            } elseif(!$result) {
                ShopAccount::where('id',$shopaccountid)
                    ->update(['allinpaynumber'=>$allinpaynumber,'status'=>'2','content'=>'参数错误，银行卡或姓名无效！','bankcard'=>$shop['bankcard'],'cardholder'=>$shop['cardholder'],'accounttime'=>date('Y-m-d H:i:s',time())]);
            } else {
                ShopAccount::where('id',$shopaccountid)
                    ->update(['allinpaynumber'=>$allinpaynumber,'status'=>'2','content'=>$result['AIPG']['INFO']['ERR_MSG'],'contentjson'=>json_encode($result),'bankcard'=>$shop['bankcard'],'cardholder'=>$shop['cardholder'],'accounttime'=>date('Y-m-d H:i:s',time())]);
            }
            return ['status'=>'success','message'=>$result['AIPG']['INFO']['ERR_MSG']];
        } elseif($data['status'] == '3') {
            return ['status'=>'failed','message'=>'打款失败，该订单正在处理中！'];
        } else {
            return ['status'=>'failed','message'=>'打款失败！'];
        }
    }
    //提现时刷新商家状态
    public static function shopRefreshWithdrawStatus() {
        $shopaccount = ShopAccount::where('status','2')->get();
        if($shopaccount) {
            foreach ($shopaccount as $v) {
                $allinpaytooles = new AllInPayTooles();
                $result = $allinpaytooles->getPayStatus($v['allinpaynumber']);
                if(@$result['AIPG']['QTRANSRSP']['QTDETAIL']['RET_CODE'] == '0000') {
                    ShopAccount::where('id', $v['id'])
                        ->update(['status' => '1', 'content' => $result['AIPG']['QTRANSRSP']['QTDETAIL']['ERR_MSG'], 'contentjson' => json_encode($result)]);
                    $shop = Shop::where('id',$v['shopid'])->first();
                    SmsMessage::accountToShop($shop['smsphone'],$shop['name'],$v['accountamount'],substr($shop['bankcard'], -4));
                } else {
                    if(@$result['AIPG']['QTRANSRSP']['QTDETAIL']['RET_CODE']) {
                        ShopAccount::where('id', $v['id'])
                            ->update(['content'=>$result['AIPG']['QTRANSRSP']['QTDETAIL']['ERR_MSG'],'contentjson'=>json_encode($result)]);
                    }
                }
            }
        }
        return ['status'=>'success','message'=>'刷新成功！'];
    }
    //商家已提现列表
    public static function shopAlreadyWithdraw($starttime = '',$lasttime = '',$search = '%',$cityId) {
        if (!$starttime || !$lasttime || !$cityId) {
            $starttime = date('Y-m-', time()) . '01 00:00:00';
            $lasttime = date('Y-m-d H:i:s', time());
        }
        if($search != '%') {
            $search = '%' . $search . '%';
        }
        $GLOBALS['search'] = $search;
        $data['shopnum'] = ShopAccount::where('shop_accounts.created_at','>=',$starttime)->where('shop_accounts.created_at','<=',$lasttime)->where('shops.cityid',$cityId)->join('shops','shops.id','=','shop_accounts.shopid')->groupBy('shop_accounts.shopid')->where('shop_accounts.status','1')->get()->count();
        $data['shopamount'] = ShopAccount::where('shop_accounts.created_at','>=',$starttime)->where('shop_accounts.created_at','<=',$lasttime)->where('shop_accounts.status','1')->where('shops.cityid',$cityId)->join('shops','shops.id','=','shop_accounts.shopid')->sum('shop_accounts.accountamount');
        $data['data'] = ShopAccount::where('shop_accounts.created_at','>=',$starttime)
            ->where('shop_accounts.created_at','<=',$lasttime)
            ->where('shops.cityid',$cityId)
            ->join('shops','shop_accounts.shopid','=','shops.id')->where('shop_accounts.status','1')
            ->where(function($query){
                $query->orWhere('shops.code','like',$GLOBALS['search'])
                    ->orWhere('shops.name','like',$GLOBALS['search']);
            })
            ->select('shops.code as shopcode','shops.name as shopname','shops.cardholder','shops.bankname','shops.bankcard','shops.bankprovince','shops.bankcity','shops.opencardbank','shop_accounts.accountamount','shop_accounts.accounttime')->get();
        return ['status'=>'success','data'=>$data];
    }
    //订单退款流程
    public static function orderRefund($orderNumber, $refundRemark) {
        if(!$orderNumber || !$refundRemark) {
            return ['status'=>'failed', 'message'=>'信息不能为空'];
        }
        if(OrderRefund::where('ordernumber', $orderNumber)->get()->count() > 0) {
            return ['status'=>'failed', 'message'=>'该订单已经退款了'];
        }
        $order = Order::where('ordernumber', $orderNumber)->where('refundstatus', 0)->first();
        if(!$order) {
            return ['status'=>'failed', 'message'=>'退款失败，稍后再试'];
        }
        //检测是否生成到已提现记录
        $GLOBALS['orderId'] = $order->id;
        $isAlreadyWithdrawal = ShopAccount::where('status', 1)->where('shopid', $order->shopid)->where(function($query){
                $query->orWhere('orderid', $GLOBALS['orderId'])->orWhere('orderid', 'like', '%,' . $GLOBALS['orderId'] . ',%')
                    ->orWhere('orderid', 'like', $GLOBALS['orderId'] . ',%')->orWhere('orderid', 'like', '%,' . $GLOBALS['orderId']);
            })->count();
        if($isAlreadyWithdrawal > 0) {
            return ['status'=>'failed', 'message'=>'该订单已给商家结算了，不能退款'];
        }
        $redEnvelopeRemark = '';
        //是否派送过红包
        //红包status=0时，表示未使用；status=1时，表示已使用；status=2时，表示已过期；status=3时，表示订单退款时，之前由订单派送出的红包的状态未使用，然后变成已失效；
        //status=4时，表示订单退款时，之前由订单派送出的红包的状态已使用，然后变成退款已使用；status=5时，表示订单退款时，之前已使用过的红包状态由已使用变成已失效
        if($order->bonusid) {
            //已派送红包
            if(Order::where('redenvelopeid', $order->bonusid)->get()->count()>0) {
                //使用了已派送的红包, 退款金额=实付金额 - 已派发红包金额
                $refundMoney = $order->actualamount - $order->bonus;
                $bonusCount = 1;
            } else {
                //未使用已派送的红包
                $refundMoney = $order->actualamount;
                $bonusCount = 0;
            }
            $bonusInfo = RedEnvelope::where('id', $order->bonusid)->first();
            if($bonusInfo && ($bonusCount == 0)) {
                $bonusInfo->status = 3;
                $bonusInfo->save();
                $redEnvelopeRemark = "本次派送的红包" . $bonusInfo->amount . '更改状态为"已失效"';
            } elseif($bonusInfo && ($bonusCount == 1)) {
                $bonusInfo->status = 4;
                $bonusInfo->save();
            }
        } else {
            //未派送红包
            $refundMoney = $order->actualamount;
        }
        //修改已使用的红包状态
        $redEnvelopeId = $order->redenvelopeid;
        if($redEnvelopeId) {
            //该订单买单时使用过红包
            $redEnvelopeInfo = RedEnvelope::where('id', $order->redenvelopeid)->first();
            if($redEnvelopeInfo) {
                //修改红包状态
                if($redEnvelopeInfo->endtime > date('Y-m-d H:i:s')) {
                    $redEnvelopeInfo->status = 5; //退款已使用变成状态5，然后产生一条新的一模一样的数据
                    $redEnvelopeInfo->save();
                    if($redEnvelopeRemark) {
                        $redEnvelopeRemark .= ",本次订单使用的红包" . $redEnvelopeInfo->amount . '更换状态为"未使用"';
                    } else {
                        $redEnvelopeRemark = "本次订单使用的红包" . $redEnvelopeInfo->amount . '更换状态为"未使用"';
                    }
                    $createRedEnvelope = RedEnvelope::create([
                        'userid' => $redEnvelopeInfo->userid,
                        'amount' => $redEnvelopeInfo->amount,
                        'shopid' => $redEnvelopeInfo->shopid,
                        'cityid' => $redEnvelopeInfo->cityid,
                        'starttime' => $redEnvelopeInfo->starttime,
                        'endtime' => $redEnvelopeInfo->endtime,
                        'usetime' => '0000-00-00 00:00:00',
                        'status' => '0',
                        'type' => $redEnvelopeInfo->type,
                        'hqamount' => $redEnvelopeInfo->hqamount,
                        'agentamount' =>$redEnvelopeInfo->agentamount,
                        'firstclassid' => $redEnvelopeInfo->firstclassid,
                        'secondclassid' => $redEnvelopeInfo->secondclassid,
                        'firstclassname' => $redEnvelopeInfo->firstclassname,
                        'secondclassname' => $redEnvelopeInfo->secondclassname,
                        'position' => $redEnvelopeInfo->position,
                        'info' => $redEnvelopeInfo->info,
                        'created_at' => date('Y-m-d H:i:s', strtotime($redEnvelopeInfo->created_at)),
                        'updated_at' => date('Y-m-d H:i:s', strtotime($redEnvelopeInfo->updated_at)),
                    ]);
                    $createRedEnvelope->save();
                } else {
                    $redEnvelopeInfo->status = 3;
                    $redEnvelopeInfo->save();
                    if($redEnvelopeRemark) {
                        $redEnvelopeRemark .= ",本次订单使用的红包" . $redEnvelopeInfo->amount . '更换状态为"已失效"';
                    } else {
                        $redEnvelopeRemark = "本次订单使用的红包" . $redEnvelopeInfo->amount . '更换状态为"已失效"';
                    }
                }
            }
        }
        $user = User::where('id', $order->userid)->first();
        if(!$user) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $startBalance = $user['balance'];
        User::where('id', $order->userid)->increment('balance', $refundMoney);
        $saveMoney = round(0.5*($order->actualamount) + $order->redenvelopeamount, 2);
        User::where('id', $order->userid)->decrement('savemoney', $saveMoney);
        $lastBalance = $startBalance + $refundMoney;
        $orderRefund = OrderRefund::create([
            'userid' => $order->userid,
            'orderid' => $order->id,
            'ordernumber' => $order->ordernumber,
            'money' => $refundMoney,
            'startbalance' => $startBalance,
            'lastbalance' => $lastBalance,
            'redenvelopeinfo' => $redEnvelopeRemark,
            'remark' => $refundRemark,
            'status' => 1,
            'adminid' => Auth::guard('adminweb')->id(),
        ]);
        $orderRefund->save();
        //修改商家表
        Shop::where('id', $order->shopid)->decrement('ordernumber', 1);
        $comment = Comment::where('userid', $order->userid)->where('shopid', $order->shopid)->where('ordernumber', $order->ordernumber)->first();
        if($comment) {
            //修改评论
            $shop = Shop::where('id', $order->shopid)->first();
            if($shop) {
                if($shop->commentnumber != 0) {
                    Shop::where('id', $order->shopid)->decrement('commentnumber',1);
                    Shop::where('id', $order->shopid)->decrement('commentscore', $comment->score);
                    $shop->commentmark = round($shop->commentscore / $shop->commentnumber, 2);
                    $shop->save();
                }
            }
            $comment->isdel = 1;
            $comment->save();
        }
        //修改订单状态
        if($redEnvelopeId) {
            $order->redenvelopeid = -$redEnvelopeId;
        }
        $order->refundstatus = 1;
        $order->save();
        //修改商家待提现
        //修改shop_accounts中的待提现数据
        $shopAccount = ShopAccount::where('status', 0)->where('shopid', $order->shopid)->where(function($query){
            $query->orWhere('orderid', $GLOBALS['orderId'])->orWhere('orderid', 'like', '%,' . $GLOBALS['orderId'] . ',%')
                ->orWhere('orderid', 'like', $GLOBALS['orderId'] . ',%')->orWhere('orderid', 'like', '%,' . $GLOBALS['orderId']);
        })->first();
        if($shopAccount) {
            if($shopAccount->accountamount > $order->accountamount) {
                $orderIdArray = explode(',', $shopAccount->orderid);
                unset($orderIdArray[array_search($order->id, $orderIdArray)]);
                $orderIdString = implode(',', $orderIdArray);
                $shopAccount->orderid = $orderIdString;
                $shopAccount->save();
                ShopAccount::where('id', $shopAccount->id)->decrement('accountamount', $order->accountamount);
            } elseif($shopAccount->accountamount == $order->accountamount) {
                $shopAccount->delete();
            }
        }
        //修改地推信息
        //商家地推
        $shopSalesmanDetail = ShopSalesmanDetail::where('type', 'order')->where('ordernumber', $orderNumber)->first();
        if($shopSalesmanDetail) {
            ShopSalesman::where('shopid', $shopSalesmanDetail->shopid)->decrement('balance', $shopSalesmanDetail->getmoney);
            ShopSalesman::where('shopid', $shopSalesmanDetail->shopid)->decrement('ordernum', 1);
            ShopSalesman::where('shopid', $shopSalesmanDetail->shopid)->decrement('validordernum', 1);
            ShopSalesman::where('shopid', $shopSalesmanDetail->shopid)->decrement('totalorderamount', $shopSalesmanDetail->orderamount);
            ShopSalesman::where('shopid', $shopSalesmanDetail->shopid)->decrement('getmoney', $shopSalesmanDetail->getmoney);
            ShopSalesman::where('shopid', $shopSalesmanDetail->shopid)->decrement('balance', $shopSalesmanDetail->getmoney);
            $shopSalesmanDetail->delete();
        }
        //个人地推
        $salesmanOrder = SalesmanOrder::where('orderid', $order->id)->where('isvalid', 1)->first();
        if($salesmanOrder) {
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('ordernum', 1);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('ordervalidnum', 1);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('ordermoney', $salesmanOrder->getmoney);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('ordertotalamount', $salesmanOrder->orderamount);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('totalmoney', $salesmanOrder->getmoney);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('balance', $salesmanOrder->getmoney);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('currentordernum', 1);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('currentordertotalamount', $salesmanOrder->orderamount);
            SalesmanInfo::where('salesmanid', $salesmanOrder->salesmanid)->decrement('currenttotalmoney', $salesmanOrder->getmoney);
            $salesmanOrder->isvalid = 0;
            $salesmanOrder->save();
        }
        //TODO 已生成待提现的数据怎么处理

        //修改翻倍轨迹
        if($user->firstordertime == date('Y-m-d H:i:s', strtotime($order->created_at))) {
            $user->firstordertime = '0000-00-00 00:00:00';
            $user->save();
        }

        $returnData = [
            'refundmoney' => $refundMoney,
            'redenvelopremark' => $redEnvelopeRemark
        ];
        return ['status'=>'success', 'data'=>$returnData];
    }

}